import  api from '@/api/index.js';
import {redirect} from "react-router-dom"




export default async function registAction({request}) {
    const formData = await request.formData();
    //获取表单字段
    const email = formData.get("email");
    const username = formData.get("username");
    const password = formData.get("password");


//     数据校验
    const errors = {};
    if (typeof email !== "string" || !email.includes('@')) {
        errors.email = "邮箱格式不正确";
    }
    if (typeof username !== "string" || username.length < 3) {
        errors.username = "请输入字符长度大于3位的用户名";
    }
    if (typeof password !== "string" || password.length < 6) {
        errors.password = "请输入字符长度大于6位的密码";
    }
    if (Object.keys(errors).length) return errors;
// 创建账号
    const user = Object.fromEntries(formData);
    user.avatar = "https://img2.baidu.com/it/u=1210416302,3260530728&fm=253&fmt=auto&app=138&f=GIF?w=192&h=178";
    const response = await api.user.regist(user);
    if (response && response.status !== 1) {
        throw new Error(response.message);
    }
    return  redirect('/login')
}